<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>评论区</span>
    </div>
    <div class="text item">
      <div>
        <span
          v-if="user == null"
          style="position: relative; bottom: 13px; left: 15px"
        >
          <el-avatar icon="el-icon-user-solid"></el-avatar>未登录
        </span>
        <span v-else style="position: relative; bottom: 13px; left: 15px">
          <img
            :src="this.user[0].avatar_img"
            alt=""
            style="width: 60px; height: 60px; border-radius: 50%"
          />
          <span style="position: relative; bottom: 25px; left: 20px">{{
            this.user[0].uname
          }}</span>
        </span>
      </div>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="评论：">
          <el-input
            type="textarea"
            v-model="form.desc"
          ></el-input> </el-form-item
      ></el-form>

      <span style="margin-left: 1300px; margin-right: 50px">
        <button style="width: 80px" @click="publish">发布</button>
      </span>
    </div>
    <el-card class="box-card" style="margin-top: 20px">
      <div v-for="(item, index) in newsContents" :key="index" class="text item">
        <!-- {{ userContent }} -->
        <div style="margin-top: 20px">
          <img
            :src="item.avatar_img"
            alt=""
            style="width: 50px; height: 50px; border-radius: 50%"
          />
          <span style="position: relative; bottom: 13px; left: 15px">{{
            item.uname
          }}</span>
          <span style="position: relative; bottom: 13px; left: 35px">{{
            item.comments_content
          }}</span
          ><br />
          <span
            style="position: relative; left: 90px; font-size: 13px; color: gray"
            >{{ getDates(item.post_time) }}</span
          >
          <button
            style="
              border: 0;
              background-color: #fff;
              color: red;
              margin-left: 1300px;
            "
            @click="deleteUserComment(item.comments_id)"
          >
            删除
          </button>
        </div>
      </div>
    </el-card>
  </el-card>
</template>

<script>
import { mapState } from "vuex";

export default {
  data() {
    return {
      form: {
        desc: "",
      },
      userContent: "",
      userName: "",
      userImg: "",
      newsContents: [],
    };
  },

  computed: {
    ...mapState("user", ["user"]),
  },
  created() {
    this.getNewsComment();
  },
  methods: {
    getNewsComment() {
      this.axios
        .get(
          `http://localhost:3000/comments/getComments?news_id=${this.$route.params.id}`
        )
        .then((res) => {
          this.newsContents = res.data.data;
          // this.news_id=news_id
          // console.log(1);
          // console.log(this.newsContents);
          // console.log(this.news_id);
          // console.log(news_id);
          // console.log(11);
          // console.log(this.news_id);
        })
        .catch((error) => {
          console.error(error);
        });
    },
    publish() {
      // console.log(localStorage.getItem('token'));
      if (!localStorage.getItem("token")) {
        alert("跳转到登录页");
        this.$router.push("/login");
      }
      this.axios
        .post(`http://localhost:3000/comments/addComments`, {
          uid: this.user[0].uid,
          news_id: this.$route.params.id,
          contents: this.form.desc,
        })
        .then((res) => {
          this.form.desc=""
          // 请求成功时，处理返回的数据
          this.userId = res.data.msg;
          console.log(this.userId);
          // console.log(9999);
          this.$message.success("发布成功！");
          this.getNewsComment();
        })
        .catch((error) => {
          // 请求失败时，处理错误
          console.error(error);
        });
    },
    deleteUserComment(id) {
      this.axios
        .delete(`http://localhost:3000/comments/deleteComments`, {
          data: {
            comments_id: id,
            uid: this.user[0].uid,
          },
        })
        .then((res) => {
          console.log(res.data);
          if (res.data.code === 200) {
            this.$message.success("删除成功！");
            this.getNewsComment();
          } else {
            this.$message.error("删除失败！");
          }
        });
    },
    getDates(timestamp) {
      // 创建一个新的Date对象，使用传入的时间戳（毫秒）
      var date = new Date(timestamp);
      // 使用各种Date方法获取年、月、日、时、分、秒等
      var year = date.getFullYear();
      var month = String(date.getMonth() + 1).padStart(2, "0"); // 月份是从0开始的，所以需要+1，并使用padStart确保总是两位数
      var day = String(date.getDate()).padStart(2, "0"); // 使用padStart确保总是两位数
      var hours = String(date.getHours()).padStart(2, "0"); // 使用padStart确保总是两位数
      var minutes = String(date.getMinutes()).padStart(2, "0"); // 使用padStart确保总是两位数
      var seconds = String(date.getSeconds()).padStart(2, "0"); // 使用padStart确保总是两位数
      // 创建一个格式化的日期时间字符串
      var formattedDate =
        year +
        "-" +
        month +
        "-" +
        day +
        " " +
        hours +
        ":" +
        minutes +
        ":" +
        seconds;

      // 返回格式化后的日期时间字符串
      return formattedDate;
    },
  },
};
</script>

<style></style>